/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.helpmanage.service.impl;

import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.punish.helpmanage.dto.AppHelpManageDto;
import com.icinfo.cloud.provider.punish.helpmanage.dto.AppHelpManageRequest;
import com.icinfo.cloud.provider.punish.helpmanage.dto.HelpManageDto;
import com.icinfo.cloud.provider.punish.helpmanage.dto.HelpManageUpdateDto;
import com.icinfo.cloud.provider.punish.helpmanage.enums.HelpDeptTypeEnum;
import com.icinfo.cloud.provider.punish.helpmanage.mapper.HelpManageMapper;
import com.icinfo.cloud.provider.punish.helpmanage.mapper.HelpTypeManageMapper;
import com.icinfo.cloud.provider.punish.helpmanage.model.HelpManage;
import com.icinfo.cloud.provider.punish.helpmanage.service.IHelpManageService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CasePartiesRecordSingleQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainDetailInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailInfo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 描述:  help_manage 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年12月11日
 */
@Service
public class HelpManageServiceImpl extends MyBatisServiceSupport implements IHelpManageService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(HelpManageServiceImpl.class);

    @Resource
    private HelpManageMapper helpManageMapper;
    @Resource
    private HelpTypeManageMapper helpTypeManageMapper;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;

    /**
     * 描述：个人帮扶-新增/修改(传主键id)
     * @param manageDto
     * @return
     * @author wangfawei
     * @date 2022-12-11
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Result<String> save(HelpManageDto manageDto) {
        try {
            UserDTO userDTO =  UserUtil.getUserInfo();
            if(ObjectUtils.isEmpty(userDTO)){
              return   Result.error("获取用户信息失败");
            }
            HelpManage manage = new HelpManage();
            BeanUtils.copyProperties(manageDto,manage);
            CasePartiesRecordSingleQueryDto queryDto = new CasePartiesRecordSingleQueryDto();
            queryDto.setPartyIdentityCode(manage.getHelpCerno());
            List<CaseMainDetailInfo> mainDetailInfoList = caseMainDetailInfoMapper.getCaseMainDetailInfoListByCaseIdAndOrder(manage.getHelpCerno());
            if(mainDetailInfoList.size()>0) {
                CaseMainDetailInfo mainDetailInfo = mainDetailInfoList.get(0);
                manage.setCaseHappenTime(mainDetailInfo.getCaseHappenTime());
                manage.setCaseReason(mainDetailInfo.getCaseReason());
                manage.setCaseAmount(String.valueOf(mainDetailInfoList.size()));
            }else{
                manage.setCaseAmount(String.valueOf(0));
            }
            manage.setId(BaseUtil.createUid());
            manage.setCreateTime(DateUtil.getCurrLocalDateTime());
            manage.setCreateUserId(String.valueOf(userDTO.getUserId()));
            manage.setOrgCode(userDTO.getOrgCode());
            manage.setOrgName(userDTO.getOrgName());
            manage.setIsDelete(Constant.STRING_0);
            manage.setUpdateTime(DateUtil.getCurrLocalDateTime());
            int res = helpManageMapper.insert(manage);
            if(res>0) {
                return Result.success(Constant.STRING_OPERATE_SUCCESS);
            }else{
                return Result.error(Constant.STRING_OPERATE_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("保存或更新补录-告知失败");
        }
        return Result.error(Constant.STRING_OPERATE_FAIL);
    }
    /**
     * 【V1.6.0】描述：个人帮扶列表
     * @param manageDto 入参
     * @return List<HelpManageDto>
     * @author 王发魏
     * @date 2022-12-09
     **/
    @Override
    public List<HelpManageDto> getHelpManageList(HelpManageDto manageDto) {
        PageHelper.startPage(manageDto.getPageNum(), manageDto.getLength());
        List<HelpManageDto> helpManageList = helpManageMapper.getHelpManageList(manageDto);
        helpManageList.forEach(help -> {
            help.setDeptTypeName(HelpDeptTypeEnum.getValueByCode(help.getDeptType()));
        });
        return helpManageList;
    }

    /**
     * 【V1.6.0】描述：删除
     * @param id 入参
     * @return ResultString
     * @author yehuafei
     * @date 2022-12-12
     **/
    @Override
    public int deleteById(String id) {
        if (StringUtils.isEmpty(id)) {
            return 0;
        }
        HelpManage build = HelpManage.builder()
                .id(id)
                .isDelete(Constant.STRING_1)
                .build();
        return helpManageMapper.updateByPrimaryKeySelective(build);
    }

    /**
     * 描述：单位帮扶-修改(传主键id) sourceType 0 个人 1 单位
     * @param updateDto
     * @return
     * @author yehuafei
     * @date 2022-12-12
     */
    @Override
    public Result<String> update(HelpManageUpdateDto updateDto) {
        HelpManage helpManage = new HelpManage();
        BeanUtils.copyProperties(updateDto,helpManage);
        helpManage.setUpdateTime(DateUtil.getCurrLocalDateTime());
        helpManageMapper.updateByPrimaryKeySelective(helpManage);
        return Result.success("更新成功");
    }

    /**
     * 【V1.6.0】描述：APP帮扶对象查询
     * @author yehuafei
     * @date 2022-12-12
     **/
    @Override
    public AppHelpManageDto getAppHelpManage(AppHelpManageRequest request) {
        Example example = new Example(HelpManage.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sourceType", request.getSourceType());
        criteria.andEqualTo("helpUserName", request.getHelpUserName());
        criteria.andEqualTo("helpCerno", request.getHelpCerno());
        criteria.andEqualTo("isDelete", Constant.STRING_0);
        if (request.getSourceType().equals(Constant.STRING_1)){
            criteria.andEqualTo("deptType",request.getDeptType());
        }
        List<HelpManage> helpManages = helpManageMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(helpManages) && helpManages.size() > 0){
            AppHelpManageDto helpManageDto = new AppHelpManageDto();
            BeanUtils.copyProperties(helpManages.get(0),helpManageDto);
            helpManageDto.setHelpTypeName(helpTypeManageMapper.selectByPrimaryKey(helpManageDto.getHelpType()).getTypeName());
            if (request.getSourceType().equals(Constant.STRING_1)){
                helpManageDto.setDeptTypeName(HelpDeptTypeEnum.getValueByCode(helpManageDto.getDeptType()));
            }
            return helpManageDto;
        }
        return null;
    }
}
